package com.ilink.teacherservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ilink.ilinkcommon.domain.PO.studyservice.*;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkapi.dto.teacher.SortOrderUpdateDTO;
import com.ilink.teacherservice.mapper.*;
import com.ilink.teacherservice.service.StudyCourseFileService;
import com.ilink.teacherservice.service.videoTranscription.FileTranscriptionService;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class StudyCourseFileServiceImpl implements StudyCourseFileService {


    @Autowired
    private StudyWebSourseMapper studyWebSourseMapper;
    @Autowired
    private StudyCourseFileMapper studyCourseFileMapper;
    @Autowired
    private StudyFileSourceMapper studyFileSourceMapper;
    @Autowired
    private CourseSourceMapper courseSourceMapper;


    @Autowired
    private OssService ossService;
    @Autowired
    private FileTranscriptionService fileTranscriptionService;

    @Autowired
    private StudyResourceSortMapper studyResourceSortMapper;




    @Override
    @Transactional
    public boolean updateSortOrder(Long parentId, List<Long> sortedIds) {
        try {
            // 遍历 sortedIds 列表，并根据前端提供的顺序更新 sortOrder
            for (int i = 0; i < sortedIds.size(); i++) {
                Long resourceId = sortedIds.get(i);

                // 查找资源的 sortOrder 记录
                StudyResourceSort resourceSort = studyResourceSortMapper.selectOne(
                        new QueryWrapper<StudyResourceSort>()
                                .eq("file_id", parentId)
                                .eq("resource_id", resourceId)
                );

                if (resourceSort != null) {
                    // 更新 sortOrder 为前端传递的顺序，从 1 开始
                    resourceSort.setSortOrder(i + 1);
                    studyResourceSortMapper.updateById(resourceSort); // 更新数据库中的记录
                }
            }
            return true;
        } catch (Exception e) {
            log.error("更新排序失败", e);
            return false;
        }
    }


    private void moveResourcesInSection(Long sectionId, StudyCourseFile newFolder, String originalSectionPath, String newSectionPath) {
        // 移动文档资源
        List<StudyFileSource> documents = studyFileSourceMapper.selectList(new QueryWrapper<StudyFileSource>().eq("file_id", sectionId));
        for (StudyFileSource document : documents) {
            // 更新FileId
            document.setFileId(newFolder.getCourseFileId());
            studyFileSourceMapper.updateById(document);
        }

        // 移动音视频资源
        List<CourseSource> audioVideoResources = courseSourceMapper.selectList(new QueryWrapper<CourseSource>().eq("file_id", sectionId));
        for (CourseSource resource : audioVideoResources) {
            // 更新FileId
            resource.setFileId(newFolder.getCourseFileId());
            courseSourceMapper.updateById(resource);
        }

        // 移动网页资源
        List<StudyWebSourse> webResources = studyWebSourseMapper.selectList(new QueryWrapper<StudyWebSourse>().eq("file_id", sectionId));
        for (StudyWebSourse webResource : webResources) {
            // 更新FileId和路径
            webResource.setFileId(newFolder.getCourseFileId());
//            webResource.setWebSoursePath(webResource.getWebSoursePath().replace(originalSectionPath, newSectionPath));
            studyWebSourseMapper.updateById(webResource);
        }

        // 递归处理子文件夹（现在不需要，因为只需要变动父文件夹id）
//        List<StudyCourseFile> subFolders = studyCourseFileMapper.selectList(new QueryWrapper<StudyCourseFile>().eq("parent_id", sectionId));
//        for (StudyCourseFile subFolder : subFolders) {
//            String newSubFolderPath = newSectionPath + subFolder.getCourseFileId() + "/";
//            subFolder.setFilePath(newSubFolderPath);
//            studyCourseFileMapper.updateById(subFolder);
//
//            // 递归移动子文件夹中的资源
//            moveResourcesInSection(subFolder.getCourseFileId(), subFolder, originalSectionPath, newSubFolderPath);
//        }
    }
    @Override
    @Transactional
     public R moveSection(Long sectionId, Long targetChapterId, Long courseId, int sortOrder) {
        try {
            // 获取当前小节和目标章节的信息
            StudyCourseFile sectionFolder = studyCourseFileMapper.selectById(sectionId);
            StudyCourseFile targetChapterFolder = studyCourseFileMapper.selectById(targetChapterId);
            if (sectionFolder == null || targetChapterFolder == null) {
                return R.error("无效的章节或小节ID");
            }

            // 确保目标章节和小节在同一课程下
            if (!sectionFolder.getCourseId().equals(courseId) || !targetChapterFolder.getCourseId()
                .equals(courseId)) {
                return R.error("目标章节与小节不属于同一课程");
            }
            // 保存原始文件路径
            String originalSectionPath = sectionFolder.getFilePath();

            // 生成新的文件路径
            String newSectionPath = targetChapterFolder.getFilePath() + sectionFolder.getCourseFileId() + "/";

            sectionFolder.setParentId(targetChapterId);
            studyCourseFileMapper.updateById(sectionFolder);

            //修改该移动文件夹的sort表中信息
            //TDDO 保证唯一性
            StudyResourceSort studyResourceSort = studyResourceSortMapper.selectOne(
                new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,
                    sectionId).eq(StudyResourceSort::getResourceType, "folder"));
            studyResourceSort.setSortOrder(sortOrder + 1);
            studyResourceSort.setFileId(targetChapterId);
            studyResourceSortMapper.update(studyResourceSort,
                new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,
                    sectionId));

            // 更新小节中的所有资源的路径和FileId
            moveResourcesInSection(sectionId, sectionFolder, originalSectionPath, newSectionPath);
        } catch (Exception e) {
            // 如果MySQL操作失败，尝试回滚操作
            log.error("目录MySQL更新失败并回滚操作", e);
            throw new RuntimeException("MySQL更新失败并回滚操作", e);
        }
        return R.ok("小节移动成功");
    }


    @Transactional
    @Override
    public R moveDocumentResource(Long resourceId, StudyCourseFile newFolder, Long courseId,int sortOrder) {
        try{
            // 获取文档资源
            StudyFileSource fileSource = studyFileSourceMapper.selectById(resourceId);
            if (fileSource == null) {
                log.error("无效文档资源ID");
                return R.error("无效文档资源ID");
            }
            // 更改文档资源的目录ID
            fileSource.setFileId(newFolder.getCourseFileId());
            studyFileSourceMapper.updateById(fileSource);

            //更改资源对应的sort表数据
            StudyResourceSort studyResourceSort = studyResourceSortMapper.selectOne(new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,resourceId).eq(StudyResourceSort::getResourceType,"word"));
            studyResourceSort.setSortOrder(sortOrder+1);
            studyResourceSort.setFileId(newFolder.getCourseFileId());
            studyResourceSortMapper.update(studyResourceSort,new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,resourceId));

            return R.ok("移动文档资源成功", resourceId);
        }catch (Exception e){
            log.error("函数moveDocumentResource报错"+e);
            return R.error("函数moveDocumentResource报错"+e);
        }
    }

    @Transactional
    @Override
    public R moveAudioVideoResource(Long resourceId, StudyCourseFile newFolder, Long courseId,int sortOrder) {
        try{
            // 获取音视频资源
            CourseSource courseSource = courseSourceMapper.selectById(resourceId);
            if (courseSource == null) {
                log.error("无效音视频资源ID");
                return R.error("无效音视频资源ID");
            }

            // 更改音视频资源的目录ID
            courseSource.setFileId(newFolder.getCourseFileId());
            courseSource.setUpdatedAt(new Date());
            courseSourceMapper.updateById(courseSource);

            //更改资源对应的sort表数据
            StudyResourceSort studyResourceSort = studyResourceSortMapper.selectOne(new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,resourceId).eq(StudyResourceSort::getResourceType,"video"));
            studyResourceSort.setSortOrder(sortOrder+1);
            studyResourceSort.setFileId(newFolder.getCourseFileId());
            studyResourceSortMapper.update(studyResourceSort,new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,resourceId));

            log.info("音视频资源移动成功");
            return R.ok("音视频资源移动成功");
        }catch (Exception e){
            log.error("函数moveAudioVideoResource报错"+e);
            return R.error("函数moveAudioVideoResource报错"+e);
        }
    }

    @Transactional
    @Override
    public R moveWebResource(Long resourceId, StudyCourseFile newFolder, Long courseId,int sortOrder) {

        try {
            // 获取网页资源
            StudyWebSourse webSource = studyWebSourseMapper.selectById(resourceId);
            if (webSource == null) {
                return R.error("无效网页资源ID");
            }

            // 更改网页资源的目录ID
            webSource.setFileId(newFolder.getCourseFileId());
            // 更新上传时间
            webSource.setUploadedAt(new Date());
            studyWebSourseMapper.updateById(webSource);

            //更改资源对应的sort表数据
            StudyResourceSort studyResourceSort = studyResourceSortMapper.selectOne(new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,resourceId).eq(StudyResourceSort::getResourceType,"web"));
            studyResourceSort.setSortOrder(sortOrder+1);
            studyResourceSort.setFileId(newFolder.getCourseFileId());
            studyResourceSortMapper.update(studyResourceSort,new LambdaQueryWrapper<StudyResourceSort>().eq(StudyResourceSort::getResourceId,resourceId));
        } catch (Exception e) {
            return R.error("网页数据库更新失败", e);
        }
        return R.ok("网页资源移动成功");
    }
}
